package com.party.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.party.common.entity.MyPage;
import com.party.common.utils.PageUtil;
import com.party.entity.*;
import com.party.entity.dto.DistributeDto1;
import com.party.entity.dto.QueryDeviceDto;
import com.party.mapper.PbDeviceMapper;
import com.party.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.party.util.MoJiCommonUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 设备管理 服务实现类
 * </p>
 *
 * @author ccl
 * @since 2024-10-25
 */
@Service
public class PbDeviceServiceImpl extends ServiceImpl<PbDeviceMapper, PbDevice> implements PbDeviceService {

    @Resource
    private PbUserService pbUserService;

    @Resource
    private PbUserDeviceService pbUserDeviceService;

    @Resource
    private PbResourceService pbResourceService;

    @Resource
    private PbResourceDeviceService pbResourceDeviceService;

    @Resource
    private PbStationDeviceService pbStationDeviceService;

    @Resource
    private PbBannerService pbBannerService;

    @Override
    public boolean add(PbDevice pbDevice) {
        PbDevice pbDevice1=this.getOne(new LambdaQueryWrapper<PbDevice>()
        .eq(PbDevice::getDeviceCode,pbDevice.getDeviceCode()));
        if(pbDevice1 !=null){
            throw new RuntimeException("设备已存在,请核查!");
        }
//        LambdaQueryWrapper<PbDevice> wrapper = new LambdaQueryWrapper<>();
//        wrapper.orderByDesc(PbDevice::getDeviceCode);
//        List<PbDevice> deviceList = this.list(wrapper);
//        if (!deviceList.isEmpty()) {
//            int code=Integer.parseInt(deviceList.get(0).getDeviceCode().substring(1));
//            String deviceCode = String.format("%06d",  code+ 1);
//            pbDevice.setDeviceCode("D"+deviceCode);
//        }else{
//            pbDevice.setDeviceCode("D000001");
//        }
        pbDevice.setOperatorId(MoJiCommonUtils.getUserCode());
        pbDevice.setCreateTime(new Date());
        pbDevice.setUpdateTime(new Date());

        return this.save(pbDevice);
    }

    @Override
    public boolean edit(PbDevice pbDevice) {
        PbDevice pbDevice1=this.getById(pbDevice.getId());
        if(!pbDevice.getDeviceName().equals(pbDevice1.getDeviceName())){
            PbDevice pbDevice2=this.getOne(new LambdaQueryWrapper<PbDevice>()
                    .eq(PbDevice::getDeviceName,pbDevice.getDeviceName()));
            if(pbDevice2 !=null){
                throw new RuntimeException("设备已存在,请核查!");
            }
        }
        BeanUtils.copyProperties(pbDevice,pbDevice1);
        pbDevice1.setOperatorId(MoJiCommonUtils.getUserCode());
        pbDevice.setUpdateTime(new Date());
        return this.updateById(pbDevice1);
    }

    @Override
    public boolean delete(Long id) {
        return this.removeById(id);
    }

    @Override
    public MyPage<PbDevice> queryPage(QueryDeviceDto dto) {
        LambdaQueryWrapper<PbDevice> wrapper = new LambdaQueryWrapper<>();
        if (ObjectUtil.isNotEmpty(dto.getDeviceName())) {
            wrapper.like(PbDevice::getDeviceName, dto.getDeviceName());
        }
        if (ObjectUtil.isNotEmpty(dto.getBelongUser())) {
            wrapper.like(PbDevice::getBelongUser, dto.getBelongUser());
        }
        if (ObjectUtil.isNotEmpty(dto.getSfBelong())) {
            if(dto.getSfBelong() ==0){
                wrapper.isNull(PbDevice::getBelongUser);
            }
            if(dto.getSfBelong() ==1){
                wrapper.isNotNull(PbDevice::getBelongUser);
            }
        }
        //管理员查看全部,非管理员查看各自的
        String loginId=MoJiCommonUtils.getLoginId();
        if(!"admin".equals(loginId)){
            PbUser pbUser=pbUserService.getOne(new LambdaQueryWrapper<PbUser>()
                    .eq(PbUser::getUserCode,MoJiCommonUtils.getUserCode()));
            if(pbUser !=null){
                List<PbUserDevice> pbUserDevices=pbUserDeviceService.list(
                        new LambdaQueryWrapper<PbUserDevice>()
                                .eq(PbUserDevice::getUserId,pbUser.getId()));
                if(ObjectUtil.isEmpty(pbUserDevices)){
                    wrapper.eq(PbDevice::getId, 0);
                }else{
                    List<Long> idList=pbUserDevices.stream().map(PbUserDevice::getDeviceId).collect(Collectors.toList());
                    if(ObjectUtil.isNotEmpty(idList)){
                        wrapper.in(PbDevice::getId, idList);
                    }
                }
            }
        }
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        wrapper.orderByDesc(PbDevice::getUpdateTime);
        List<PbDevice> deviceList = this.list(wrapper);
        if(ObjectUtil.isNotEmpty(deviceList)){
            deviceList.forEach(device->{
                List<PbStationDevice> pbStationDevices=pbStationDeviceService.list(
                        new LambdaQueryWrapper<PbStationDevice>()
                                .eq(PbStationDevice::getDeviceId,device.getId())
                .eq(PbStationDevice::getType,1));
                if(ObjectUtil.isNotEmpty(pbStationDevices)){
                    List<Long> stationIds=pbStationDevices.stream().map(PbStationDevice::getStationId).collect(Collectors.toList());
                    device.setStationIds(stationIds);
                }

                List<PbStationDevice> pbStationDevices2=pbStationDeviceService.list(
                        new LambdaQueryWrapper<PbStationDevice>()
                                .eq(PbStationDevice::getDeviceId,device.getId())
                                .eq(PbStationDevice::getType,2));
                if(ObjectUtil.isNotEmpty(pbStationDevices2)){
                    List<Long> stationIds2=pbStationDevices2.stream().map(PbStationDevice::getStationId).collect(Collectors.toList());
                    device.setElegantIds(stationIds2);
                }

                List<PbStationDevice> pbStationDevices3=pbStationDeviceService.list(
                        new LambdaQueryWrapper<PbStationDevice>()
                                .eq(PbStationDevice::getDeviceId,device.getId())
                                .eq(PbStationDevice::getType,3));
                if(ObjectUtil.isNotEmpty(pbStationDevices3)){
                    List<Long> stationIds3=pbStationDevices3.stream().map(PbStationDevice::getStationId).collect(Collectors.toList());
                    device.setPosterIds(stationIds3);
                }

                List<PbStationDevice> pbStationDevices4=pbStationDeviceService.list(
                        new LambdaQueryWrapper<PbStationDevice>()
                                .eq(PbStationDevice::getDeviceId,device.getId())
                                .eq(PbStationDevice::getType,4));
                if(ObjectUtil.isNotEmpty(pbStationDevices4)){
                    List<Long> stationIds4=pbStationDevices4.stream().map(PbStationDevice::getStationId).collect(Collectors.toList());
                    device.setThemeIds(stationIds4);
                }

                List<PbResourceDevice> pbResourceDevices=pbResourceDeviceService.list(
                        new LambdaQueryWrapper<PbResourceDevice>()
                                .eq(PbResourceDevice::getDeviceId,device.getId()));
                if(ObjectUtil.isNotEmpty(pbResourceDevices)){
                    List<Long> resourceIds=pbResourceDevices.stream().map(PbResourceDevice::getResourceId).collect(Collectors.toList());
                    device.setResourceIds(resourceIds);
                }
            });
        }
        PageInfo<PbDevice> info = new PageInfo<>(deviceList);
        return PageUtil.PageInfo2MyPage(info);
    }

    @Override
    public PbDevice detail(Long id) {
        return this.getById(id);
    }

    @Override
    public boolean distribute(DistributeDto1 dto) {
        PbDevice pbDevice=this.getById(dto.getId());
        if(pbDevice==null){
            throw new RuntimeException("设备不存在,请核查!");
        }
        List<String> list1= Arrays.asList(dto.getIds().split(","));
        List<Long> list2=list1.stream().map(Long::parseLong).collect(Collectors.toList());
        if(dto.getType()==0){//资源分配
            LambdaQueryWrapper<PbResource> wrapper=new LambdaQueryWrapper<>();
            wrapper.in(PbResource::getResourceId,list2);
            List<PbResource> pbResources=pbResourceService.list(wrapper);
            List<PbResourceDevice> resourceDevices= Lists.newArrayList();
            pbResources.forEach(pbResource->{
                PbResourceDevice pbResourceDevice=new PbResourceDevice();
                pbResourceDevice.setDeviceId(dto.getId());
                pbResourceDevice.setResourceId(pbResource.getResourceId());
                resourceDevices.add(pbResourceDevice);
            });
            pbResourceDeviceService.remove(
                    new LambdaQueryWrapper<PbResourceDevice>()
                            .eq(PbResourceDevice::getDeviceId,dto.getId())
                            .in(PbResourceDevice::getResourceId,list2));
            pbResourceDeviceService.saveBatch(resourceDevices);
        }else{//自控电台、党建、海报分配、主题日志
            LambdaQueryWrapper<PbBanner> wrapper=new LambdaQueryWrapper<>();
            wrapper.in(PbBanner::getId,list2);
            List<PbBanner> pbBanners=pbBannerService.list(wrapper);
            List<PbStationDevice> stationDevices=new ArrayList<>();
            pbBanners.forEach(pbBanner->{
                PbStationDevice pbStationDeviceOld=pbStationDeviceService.getOne(
                    new LambdaQueryWrapper<PbStationDevice>()
                            .in(PbStationDevice::getStationId,pbBanner.getId()));
                if(pbStationDeviceOld==null){
                    PbStationDevice pbStationDevice=new PbStationDevice();
                    pbStationDevice.setDeviceId(dto.getId());
                    pbStationDevice.setStationId(pbBanner.getId());
                    pbStationDevice.setType(pbBanner.getType());
                    stationDevices.add(pbStationDevice);
                }
            });
            pbStationDeviceService.saveBatch(stationDevices);
        }
        return true;
    }
}
